<template>
  <div class="productDetail-header">
    <img
      crossOrigin="anonymous"
      src="../assets/xwimg/back.png"
      alt="header"
      class="header-img"
    />
    <span class="back-btn">
      专注进出口贸易数据统计分析，一站式数据查询平台
    </span>
  </div>

  <div class="common-layout" v-loading="isloading">
    <div class="main">
      <div class="doc-preview-wrapper">
        <!-- 顶部信息栏 -->
        <div class="doc-header">
          <el-icon class="close-icon" @click="closeWindow">
            <Close />
          </el-icon>
          <div class="doc-title-line">
            <span class="iconfont icon-icon_pdf"></span>
            <h1 class="doc-title">{{ docInfo.title }}</h1>
          </div>
          <div class="doc-info-line">
            <span>
              <el-icon><Document /></el-icon> 共{{ docInfo.sizeNum }}页
            </span>
            <span>
              <el-icon><Calendar /></el-icon>
              {{ dayjs.unix(docInfo.publishTime).format("YYYY-MM-DD") }}
            </span>
            <el-button
              link
              size="small"
              :icon="isCollected ? StarFilled : Star"
              :type="isCollected ? 'danger' : 'primary'"
              @click="toggleCollect"
            >
              {{ isCollected ? "已收藏" : "收藏" }}
            </el-button>
            <el-button link size="small" @click="handleShare">分享</el-button>
            <el-button link size="small" @click="handleNote"
              >截图记笔记</el-button
            >
            <el-button
              type="primary"
              text
              class="download-btn"
              @click="handleDownload"
            >
              <el-icon><Download /></el-icon> 下载报告
            </el-button>
          </div>
          <el-alert type="info" show-icon :closable="false" class="alert-box">
            <template #title>
              <div class="alert-title">
                温馨提示：本文档最多预览
                <span class="alert-pages">{{ totalPages }}</span>
                页，点击下载查看全部内容
              </div>
            </template>
          </el-alert>
        </div>

        <!-- 内容预览 -->
        <div class="doc-content">
          <vue-pdf-embed
            :source="docInfo.pdfdir"
            :page="currentPage"
            class="pdf-container"
            style="width: 100%; height: 580px"
          />
          <div class="pdf-controls" v-if="totalPages > 0">
            <el-button @click="prevPage" :disabled="currentPage <= 1">
              上一页
            </el-button>
            <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
            <el-button @click="nextPage" :disabled="currentPage >= totalPages">
              下一页
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 侧栏：相关文档、介绍、笔记 -->
    <el-card class="side-card">
      <template #header>
        <div class="side-header">
          <span class="side-title">文档信息</span>
        </div>
      </template>
      <el-tabs v-model="activeName" class="enhanced-tabs">
        <el-tab-pane label="相关文档" name="first">
          <div class="scroll-container">
            <el-row
              v-for="item in documentList"
              :key="item.id"
              class="document-item"
            >
              <el-col :span="6">
                <div class="img-wrapper">
                  <img
                    crossOrigin="anonymous"
                    :src="item.coverPic"
                    alt="Document"
                    class="document-image"
                  />
                  <div class="img-title">{{ item.title }}</div>
                </div>
              </el-col>
              <el-col :span="18">
                <div class="document-info">
                  <p class="doc-title">
                    <span class="iconfont icon-icon_pdf"></span>
                    <router-link
                      class="doc-title-link"
                      :to="{
                        name:
                          item.price === '0'
                            ? 'productDetail'
                            : 'productDetailcharge',
                        params: { code: item.code },
                      }"
                    >
                      {{ item.title }}
                    </router-link>
                  </p>
                  <div class="doc-meta">
                    <span class="meta-text">
                      <el-icon><User /></el-icon> {{ item.author }}
                    </span>
                    <span class="meta-text">
                      <el-icon><Calendar /></el-icon>
                      {{ dayjs.unix(item.publishTime).format("YYYY-MM-DD") }}
                    </span>
                    <span class="meta-text">
                      <el-icon><Document /></el-icon> {{ item.sizeNum }}页
                    </span>
                  </div>
                  <el-tag class="custom-tag" effect="dark">
                    {{ item.PM_industry_1_name || "未分类" }}
                  </el-tag>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="文档介绍" name="second">
          <div class="document-intro-box">
            <h2 class="intro-title">
              <span class="iconfont icon-icon_pdf"></span>
              {{ docInfo.title }}
            </h2>
            <ul class="intro-list">
              <li>
                <span class="label">所属行业：</span>
                <el-tag size="small" class="blue-tag">
                  {{ docInfo.PM_industry_1_name }}
                </el-tag>
                <template v-if="docInfo.PM_industry_2_name">
                  <span class="divider">--</span>
                  <el-tag size="small" class="blue-tag">
                    {{ docInfo.PM_industry_2_name }}
                  </el-tag>
                </template>
              </li>
              <li>
                <span class="label">发布作者/机构：</span>{{ docInfo.author }}
              </li>
              <li>
                <span class="label">发布时间：</span
                >{{ dayjs.unix(docInfo.publishTime).format("YYYY-MM-DD") }}
              </li>
              <li>
                <span class="label">报告页码：</span>{{ docInfo.sizeNum }}页
              </li>
            </ul>
          </div>
        </el-tab-pane>

        <el-tab-pane label="笔记" name="third">
          <div style="height: 600px; overflow-y: auto">
            <ScreenShot ref="screenshotRef" @pushImgToNote="pushImgToNote" />
            <template v-if="screenImgList.length > 0">
              <div
                class="note-wrapper"
                v-for="item in screenImgList"
                :key="item.notePic"
              >
                <img
                  crossOrigin="anonymous"
                  :src="item.notePic"
                  alt="Note"
                  class="note-image"
                />
                <div style="display: flex; align-items: center; gap: 8px">
                  <el-input
                    v-model="item.noteTxt"
                    placeholder="请输入笔记内容，按回车保存"
                    class="note-input"
                    :disabled="item.saving || item.saved"
                    @keyup.enter="saveNote(item)"
                  />
                  <el-button
                    type="primary"
                    @click="saveNote(item)"
                    :loading="item.saving"
                    :disabled="item.saving || item.saved"
                  >
                    {{ item.saved ? "已保存" : "保存" }}
                  </el-button>
                </div>
              </div>
            </template>
            <template v-else>
              <el-empty
                description="当前暂无笔记，点击“截图记笔记”试试"
                style="margin-top: 100px"
              />
            </template>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";

import VuePdfEmbed from "vue-pdf-embed";
import ScreenShot from "./components/ScreenShot.vue";

import {
  User,
  Calendar,
  Document,
  Back,
  Star,
  StarFilled,
  Download,
} from "@element-plus/icons-vue";

import { reportApi } from "../api/report.js";

const router = useRouter();
const route = useRoute();

const isloading = ref(true);
const activeName = ref("first");
const docInfo = ref({});
const documentList = ref([]);
const screenImgList = ref([]);

const isCollected = ref(false);
const currentPage = ref(1);
const totalPages = ref(0);
const screenshotRef = ref(null);
const closeWindow = () => {
  window.close();
}


// 通用拉数据函数
async function fetchData(code) {
  isloading.value = true;
  try {
    const [detailRes, relatedRes] = await Promise.all([
      reportApi.getReportDetail({ code }),
      reportApi.getRelatedReports({ code }),
    ]);
    if (detailRes.code === 0) {
      const d = detailRes.data.detail;
      docInfo.value = d;
   
      const calculatedPages =Math.ceil(Number(d.sizeNum) * 0.3);
      totalPages.value = calculatedPages > 10 ? 10 : calculatedPages;
      screenImgList.value = (d.userNote || []).map((n) => ({
        notePic: n.notePic,
        noteTxt: n.noteTxt || "",
        saving: false,
        saved: !!n.noteTxt,
      }));
      isCollected.value = !!d.userCollectTime;
    }
    if (relatedRes.code === 0) {
      documentList.value = relatedRes.data.listRelate;
    }
  } finally {
    isloading.value = false;
  }
}

onMounted(() => {
  fetchData(route.params.code);
});

// 监听路由 param.code 变化
watch(
  () => route.params.code,
  (newCode) => {
    fetchData(newCode);
    currentPage.value = 1;
  }
);

// 分页控制
const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--;
};
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  } else {
    ElMessage.warning("已达到预览上限，下载后可查看完整内容");
  }
};

// 收藏、分享、笔记、下载等
const toggleCollect = async () => {
  try {
    await reportApi.reportcollect({ code: route.params.code });
    isCollected.value = !isCollected.value;
    ElMessage.success(isCollected.value ? "收藏成功" : "已取消收藏");
  } catch {
    ElMessage.error("操作失败，请重试");
  }
};

const handleShare = async () => {
  const url = window.location.href;
  try {
    await navigator.clipboard.writeText(url);
    ElMessage.success('链接已复制到剪贴板');
  } catch {
    // 兼容处理
    const input = document.createElement('input');
    input.value = url;
    document.body.appendChild(input);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
    ElMessage.success('链接已复制');
  }
};


const handleNote = () => {
  activeName.value = "third";
  screenshotRef.value.startScreenshot();
};

const pushImgToNote = (imgItem) => {
  screenImgList.value.push({
    notePic: imgItem.img,
    noteTxt: "",
    saving: false,
    saved: false,
  });
};

const saveNote = async (item) => {
  if (!item.noteTxt.trim()) {
    ElMessage.warning("请先输入笔记内容");
    return;
  }
  item.saving = true;
  try {
    const res = await reportApi.reportNote({
      code: route.params.code,
      notePic: item.notePic,
      noteTxt: item.noteTxt.trim(),
    });
    if (res.code === 0) {
      item.saved = true;
      ElMessage.success("笔记已保存");
    } else {
      throw new Error(res.message);
    }
  } catch (err) {
    ElMessage.error(err.message || "保存笔记失败");
  } finally {
    item.saving = false;
  }
};

const handleDownload = async () => {
  try {
    const res = await reportApi.reportDownload({ code: route.params.code });
    if (res.code === 0) {
      const a = document.createElement("a");
      a.href = res.data.userDown.pdfDir;
      a.download = "";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      ElMessage.success("下载开始");
    } else {
      ElMessage.error(res.msg || "下载失败");
    }
  } catch {
    ElMessage.error("下载出错");
  }
};
</script>

<style lang="scss" scoped>
.productDetail-header {
  height: 70px;
  // background: url("../assets/xwimg/productView.png") center/cover no-repeat;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  position: relative;
  .header-img {
    width: 100%;
    height: 70px;
    z-index: -1;
    object-fit: cover;
    position: absolute;
    top: 0;
    left: 0;
  }
  .back-btn {
    margin: 0 auto;
    font-size: 30px;
    font-weight: 600;
    color: #004d7d;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);

    .el-icon {
      transition: transform 0.3s;
    }

    &:hover .el-icon {
      transform: translateX(-3px);
    }
  }
}

.common-layout {
  display: flex;
  align-items: stretch;
  justify-content: center;
  margin: 0 auto;
  height: 95vh; // 减去 header 高度
  width: 80%;
  padding: 30px;
  box-sizing: border-box;
  gap: 24px;

  .main {
    width: 70%;
    // overflow-y: auto;
    height: 100%;
    // background: #0f58c5;
    .doc-preview-wrapper {
      width: 95%;
      height: 92.7%;
      padding: 30px;
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.06);
      display: flex;
      flex-direction: column;
      gap: 20px;

      .doc-header {
        display: flex;
        flex-direction: column;
        gap: 16px;
        position: relative;
        .close-icon {
          position: absolute;
          top: -25px;
          right: -25px;
          font-size: 30px;
          color: white;
          cursor: pointer;
          z-index: 10;
          transition: all 0.3s;

          /* 四分之一圆形设计 */
          width: 45px;
          height: 45px;
          display: flex;
          align-items: flex-start;
          justify-content: flex-end;
          padding: 15px;
          clip-path: circle(100% at 100% 0%);
          background-color: #949597; /* 灰色背景 */
          box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
          border-radius: 0 0 0 100%; /* 圆角效果 */

          /* 悬停效果 */
          &:hover {
            background-color: #ff4d4f; /* 悬停时变为红色 */

            box-shadow: 0 0 15px rgba(255, 77, 79, 0.4); /* 增强阴影效果 */
          }
        }
        .doc-title-line {
          display: flex;
          align-items: center;
          gap: 8px;

          .iconfont {
            font-size: 20px;
            color: #ff7861;
          }

          .doc-title {
            font-size: 20px;
            font-weight: 600;
            color: #2c3e50;
            margin: 0;
          }
        }

        .doc-info-line {
          display: flex;
          align-items: center;
          gap: 16px;
          flex-wrap: wrap;
          font-size: 14px;
          color: #666;

          .download-btn {
            margin-left: auto;
            font-size: 14px;
            color: #3498db;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 4px;
          }

          .el-icon {
            margin-right: 4px;
          }
        }

        .alert-box {
          font-size: 13px;
        }
      }

      .cover-image {
        width: 100%;
        max-height: 240px;
        object-fit: cover;
        border-radius: 6px;
      }

      .doc-content {
        height: 580px;
        border: 1px solid #ebeef5;
        border-radius: 4px;
        position: relative;

        .pdf-container {
          &::-webkit-scrollbar {
            width: 6px;
          }
          &::-webkit-scrollbar-track {
            background: #f1f1f1;
          }
          &::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
          }

          width: 100%;
          height: 100%;
          overflow-y: auto;
          position: relative;
          :deep(.pdf-page) {
            max-width: 85%;
            margin: 0 auto;
          }
        }

        .pdf-controls {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          height: 40px;

          background: rgba(255, 255, 255, 0.9);
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 20px;
          border-top: 1px solid #ebeef5;
        }
      }

      .download-tips {
        text-align: center;
        font-size: 14px;
        color: #3498db;
        background: #f0faff;
        border: 1px dashed #cce6ff;
        padding: 12px;
        border-radius: 8px;
      }
    }
  }

  .side-card {
    width: 30%;
    height: 100%;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    // overflow-y: auto;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    .side-header {
      padding: 20px 20px;

      .side-title {
        font-size: 18px;
        font-weight: 600;
        color: #2c3e50;
        text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
      }
    }

    .enhanced-tabs {
      :deep(.el-tabs__nav-wrap) {
        &::after {
          height: 1px;
          background-color: #ecf0f1;
        }
      }

      :deep(.el-tabs__item) {
        font-weight: 500;
        color: #7f8c8d;

        &.is-active {
          color: #3498db;
          text-shadow: 0 2px 4px rgba(52, 152, 219, 0.2);
        }
      }
      .scroll-container {
        height: 600px;
        overflow-y: auto;
        padding-right: 8px;

        /* 自定义滚动条样式 */
        &::-webkit-scrollbar {
          width: 6px;
        }
        &::-webkit-scrollbar-track {
          background: #f1f1f1;
        }
        &::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 4px;
        }
      }
    }

    .document-item {
      overflow: hidden;
      padding: 15px;
      margin: 10px 0;
      border-radius: 8px;
      transition: all 0.3s;
      background: linear-gradient(to right, #ffffff, #f8f9fa);

      &:hover {
        transform: translateX(5px);
        box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.08);
      }

      .document-image {
        width: 65px;
        height: 95px;
        // border-radius: 6px;
        object-fit: cover;
      }

      .document-info {
        padding-left: 15px;

        .doc-title {
          font-size: 16px;
          // font-weight: 600;
          color: #34495e;
          margin: 0 0 8px 0;
          text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.05);
          line-height: 1.4;
        }

        .doc-meta {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-bottom: 10px;

          .meta-text {
            display: flex;
            align-items: center;
            gap: 3px;
            font-size: 12px;
            color: #95a5a6;
          }
        }

        .custom-tag {
          border-radius: 4px;
          background: rgba(52, 152, 219, 0.1);
          border: 1px solid rgba(52, 152, 219, 0.2);
          color: #3498db;
          font-size: 12px;
          padding: 4px 8px;
        }
      }
    }

    .document-intro-box {
      padding: 20px;
      background: #f9fafa;
      border-radius: 12px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      display: flex;
      flex-direction: column;
      gap: 18px;

      .intro-title {
        font-size: 18px;
        font-weight: 600;
        color: #2c3e50;
        display: flex;
        align-items: center;
        gap: 6px;
        margin: 0;

        .iconfont {
          font-size: 20px;
          color: #ff7861;
        }
      }

      .intro-list {
        list-style: none;
        padding: 0;
        margin: 0;
        display: flex;
        flex-direction: column;
        gap: 12px;

        li {
          font-size: 14px;
          color: #34495e;

          .label {
            font-weight: 500;
            color: #7f8c8d;
            margin-right: 6px;
          }

          .el-tag {
            border-radius: 6px;
            font-size: 12px;
            font-weight: 500;
          }

          .blue-tag {
            background-color: #eaf6ff;
            border-color: #b3e5fc;
            color: #3498db;
          }
        }
      }
    }

    .note-wrapper {
      // margin: 16px 0;
      padding: 12px;
      background: #f5f7fa;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }

    .note-image {
      width: 100%;
      max-width: 600px;
      height: auto;
      border-radius: 4px;
      margin-bottom: 12px;
      display: block;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .note-input {
      width: 100%;
      max-width: 600px;
    }

    .note-input :deep(.el-input__wrapper) {
      background-color: #fff;
      box-shadow: 0 0 0 1px #dcdfe6;
    }

    .note-input :deep(.el-input__wrapper:hover) {
      box-shadow: 0 0 0 1px #c0c4cc;
    }

    .note-input :deep(.el-input__wrapper.is-focus) {
      box-shadow: 0 0 0 1px #409eff;
    }
  }
}
.icon-icon_pdf {
  color: #ff7861;
  font-size: 20px;
}
.img-wrapper {
  position: relative;

  .img-title {
    position: absolute;
    position: absolute;
    top: 30%;
    left: 35%;
    /* 先把文字中心移到容器中心 */
    transform: translate(-50%, -50%) rotate(-5deg);
    /* 文字样式 */
    font-size: 9px;
    font-weight: bold;
    font-style: italic;
    color: #fff;
    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
    white-space: nowrap;
    pointer-events: none;
    text-align: center;
    width: 60px;
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏溢出的内容 */
    text-overflow: ellipsis; /* 显示省略号来代表被修剪的文本 */
  }
}
.doc-title-link {
  text-decoration: none;
  color: inherit;
}

.doc-title-link:hover {
  text-decoration: none;
}
/* 高亮页数为红色 */
.alert-pages {
  color: #ff4d4f;
  font-weight: bold;
}
</style>
